package me.tuyou.controller;

import me.tuyou.entity.User;
import me.tuyou.servcie.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 基于注解式webflux的响应式编程
 * 此时默认的容器是netty
 * springWebFlux+reactor+netty的模式
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @GetMapping("/user/{id}")
    public Mono<User> getById(@PathVariable("id") Integer id){
        return userService.findUserById(id);
    }

    /**
     * 拿到全部
     * @return
     */
    @GetMapping("/user")
    public Flux<User> getAllUser(){
        return userService.findAllUser();
    }

    /**
     * 添加
     * @param user
     * @return
     */
    @PostMapping("/user/add")
    public Mono<Void> saveUser(@RequestBody User user){
        Mono<User> userMono=Mono.just(user);
        return userService.saveUserInfo(userMono);
    }

    @GetMapping("/hello")
    public Mono<String> hello() {
        long start = System.currentTimeMillis();
        Mono<String> hello = Mono.fromSupplier(() -> getHelloStr());
        System.out.println("接口耗时：" + (System.currentTimeMillis() - start));
        return hello;
    }

    private String getHelloStr() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hello";
    }

    @GetMapping(value = "/flux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> flux() {
        Flux<String> flux = Flux.fromArray(new String[]{"小黑","小胖","小六","一鑫"}).map(s -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "二班：" + s;
        });
        return flux;
    }
}
